package com.atyjh.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.atyjh.reggie.dto.DishDto;
import com.atyjh.reggie.dto.Result;
import com.atyjh.reggie.entity.Category;
import com.atyjh.reggie.entity.Dish;
import com.atyjh.reggie.entity.DishFlavor;
import com.atyjh.reggie.mapper.DishMapper;
import com.atyjh.reggie.service.ICategoryService;
import com.atyjh.reggie.service.IDishFlavorService;
import com.atyjh.reggie.service.IDishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yjh
 * @since jdk1.8.0_311 2022.06.16
 */
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {
    @Resource
    private IDishFlavorService dishFlavorService;

    @Resource
    private ICategoryService categoryService;

    @Resource
    private DishMapper dishMapper;

    @Override
    @Transactional
    public Result<String> saveWithFlavor(DishDto dishDto) {

//        1. 保存到dish表中
        this.save(dishDto);

//        2. 将刚刚得到的dishId赋给dish_flavor中
        Long dishId = dishDto.getId();
        List<DishFlavor> flavorList = dishDto.getFlavors()
                .stream()
                .peek(item -> item.setDishId(dishId))
                .collect(Collectors.toList());

//        2. 保存到dish_flavor表中
        dishFlavorService.saveBatch(flavorList);

        return Result.success("添加新菜品成功！");
    }

    @Override
    public Result<Page<DishDto>> pageDish(Integer page, Integer pageSize, String name) {
//        创建分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
//        创建条件构造器
        LambdaQueryWrapper<Dish> dlqw = new LambdaQueryWrapper<>();
        dlqw.like(name != null, Dish::getName, name)
                .orderByDesc(Dish::getUpdateTime);
        page(dishPage, dlqw);

//        在DishDto中添加了分类名称字段
        Page<DishDto> dishDtoPage = new Page<>();

//        将分页部分信息拷贝到dishDtoPage中（不包括records信息）
        BeanUtil.copyProperties(dishPage, dishDtoPage, "records");

//        将records信息中的categoryId在category表中找到对应的name（比如闽菜、川菜啥的）
        List<DishDto> dishList = dishPage.getRecords().stream().map(dish -> {
//            将Dish转换成DishDto
            DishDto dishDto = new DishDto();
            BeanUtil.copyProperties(dish, dishDto);
//            查询出categoryId对应的name叫什么
            Long categoryId = dishDto.getCategoryId();
            Category category = categoryService.getById(categoryId);
//            设置DishDto的categoryName值
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            } else {
                dishDto.setCategoryName("暂未分类");
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(dishList);

        return Result.success(dishDtoPage);
    }

    @Override
    public Result<DishDto> getDish(Long id) {

//        根据id获得dish
        Dish dish = getById(id);
        DishDto dishDto = new DishDto();
        BeanUtil.copyProperties(dish, dishDto);

//        根据id查询flavor
        LambdaQueryWrapper<DishFlavor> dflqw = new LambdaQueryWrapper<>();
        dflqw.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavors = dishFlavorService.list(dflqw).stream().map(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
            return dishFlavor;
        }).collect(Collectors.toList());
//        设置口味flavor
        dishDto.setFlavors(flavors);

        return Result.success(dishDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> updateWithFlavor(DishDto dishDto) {

//        更新Dish表
        updateById(dishDto);

//        删除dish_flavor表中对应口味
        LambdaQueryWrapper<DishFlavor> dflqw = new LambdaQueryWrapper<>();
        dflqw.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(dflqw);

//        设置新的口味的dishId
        List<DishFlavor> flavors = dishDto.getFlavors().stream().map(dishFlavor -> {
            dishFlavor.setDishId(dishDto.getId());
            return dishFlavor;
        }).collect(Collectors.toList());

//        保存口味
        dishFlavorService.saveBatch(flavors);

        return Result.success("更新成功！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> removeBatch(List<Long> ids) {
//        批量删除菜品
        removeBatchByIds(ids);
//        批量删除口味
        Map<String, Object> map = new HashMap<>(ids.size());
        ids.forEach(id -> {
            map.put("dish_id", id);
            dishFlavorService.removeByMap(map);
        });
        return Result.success("成功删除！");
    }

    @Override
    public Result<List<DishDto>> listDishDTO(Long categoryId) {
//        查询分类对应的菜品
        LambdaQueryWrapper<Dish> dlqw = new LambdaQueryWrapper<>();
        dlqw.eq(Dish::getCategoryId, categoryId).eq(Dish::getStatus, 1);
        List<Dish> dishList = list(dlqw);
        if (dishList == null) {
            return Result.success(Collections.emptyList());
        }
//        查询菜品对应的口味，并封装成DishDTO
        List<DishDto> dishDtoList = dishList.stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtil.copyProperties(item, dishDto);
            LambdaQueryWrapper<DishFlavor> dflqw = new LambdaQueryWrapper<>();
            dflqw.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(dflqw);
            dishDto.setFlavors(flavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return Result.success(dishDtoList);
    }


}
